// src/store/modules/groupList.js
const state = {
    // 群组列表
    list: [],
    
    // 搜索关键词
    searchKeyword: '',
    
    // 当前选中的群组
    currentId: null,
    
    // 群组成员
    groupMembers: {},
    
    // 群组设置
    groupSettings: {},
    
    // 群组邀请
    groupInvitations: {
      sent: [],
      received: []
    },
    
    // 置顶群组
    pinnedGroups: [],
    
    // 免打扰设置
    muteSettings: {},
    
    // 排序设置
    sortBy: 'name', // name, memberCount, lastActivity, createTime
    sortOrder: 'asc', // asc, desc
    
    // 过滤设置
    filterType: 'all', // all, joined, created, public, private, muted
    
    // 加载状态
    loading: false,
  }
  
  const mutations = {
    // 基础操作
    SET_LIST(state, list) {
      state.list = list
    },
    
    // 加载状态
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    
    ADD_GROUP(state, group) {
      state.list.push(group)
    },
    
    UPDATE_GROUP(state, { id, updates }) {
      const index = state.list.findIndex(group => group.id === id)
      if (index !== -1) {
        state.list[index] = { ...state.list[index], ...updates }
      }
    },
    
    REMOVE_GROUP(state, id) {
      state.list = state.list.filter(group => group.id !== id)
      // 清理相关设置
      state.pinnedGroups = state.pinnedGroups.filter(groupId => groupId !== id)
      delete state.groupMembers[id]
      delete state.groupSettings[id]
      delete state.muteSettings[id]
    },
    
    SET_SEARCH_KEYWORD(state, keyword) {
      state.searchKeyword = keyword
    },
    
    SET_CURRENT(state, id) {
      state.currentId = id
    },
    
    // 群组成员
    SET_GROUP_MEMBERS(state, { groupId, members }) {
      state.groupMembers[groupId] = members
    },
    
    ADD_GROUP_MEMBER(state, { groupId, member }) {
      if (!state.groupMembers[groupId]) {
        state.groupMembers[groupId] = []
      }
      state.groupMembers[groupId].push(member)
    },
    
    REMOVE_GROUP_MEMBER(state, { groupId, userId }) {
      if (state.groupMembers[groupId]) {
        state.groupMembers[groupId] = state.groupMembers[groupId].filter(
          member => member.id !== userId
        )
      }
    },
    
    // 群组设置
    UPDATE_GROUP_SETTINGS(state, { groupId, settings }) {
      state.groupSettings[groupId] = {
        ...state.groupSettings[groupId],
        ...settings
      }
    },
    
    // 群组邀请
    ADD_GROUP_INVITATION(state, { type, invitation }) {
      if (type === 'sent') {
        state.groupInvitations.sent.push(invitation)
      } else if (type === 'received') {
        state.groupInvitations.received.push(invitation)
      }
    },
    
    REMOVE_GROUP_INVITATION(state, { type, id }) {
      if (type === 'sent') {
        state.groupInvitations.sent = state.groupInvitations.sent.filter(inv => inv.id !== id)
      } else if (type === 'received') {
        state.groupInvitations.received = state.groupInvitations.received.filter(inv => inv.id !== id)
      }
    },
    
    // 置顶操作
    PIN_GROUP(state, id) {
      if (!state.pinnedGroups.includes(id)) {
        state.pinnedGroups.push(id)
      }
    },
    
    UNPIN_GROUP(state, id) {
      state.pinnedGroups = state.pinnedGroups.filter(groupId => groupId !== id)
    },
    
    // 免打扰操作
    MUTE_GROUP(state, { id, muteUntil }) {
      state.muteSettings[id] = {
        isMuted: true,
        muteUntil: muteUntil || null,
        muteTime: Date.now()
      }
    },
    
    UNMUTE_GROUP(state, id) {
      delete state.muteSettings[id]
    },
    
    // 排序设置
    SET_SORT_BY(state, sortBy) {
      state.sortBy = sortBy
    },
    
    SET_SORT_ORDER(state, order) {
      state.sortOrder = order
    },
    
    // 过滤设置
    SET_FILTER_TYPE(state, type) {
      state.filterType = type
    }
  }
  
  const actions = {
    // 初始化群组模块
    async initialize({ commit, state }) {

      // 防止重复初始化
      if (state.loading) {

        return;
      }
      
      commit("SET_LOADING", true);
      
      try {
        // 检查缓存
        const cachedData = localStorage.getItem("groupList_cache");
        if (cachedData) {
          const { data, timestamp } = JSON.parse(cachedData);
          if (Date.now() - timestamp < 5 * 60 * 1000) {
            commit('SET_LIST', data);

            return;
          } else {

          }
        }

        // 从服务器加载（这里需要您提供对应的API）
        // const list = await api.getGroupList()
        
        // 临时使用空数组

        const groupList = [];
        commit('SET_LIST', groupList);

        // 缓存数据
        localStorage.setItem(
          "groupList_cache",
          JSON.stringify({
            data: groupList,
            timestamp: Date.now(),
          })
        );

      } catch (error) {
        console.error("groupList 模块初始化失败:", error);

        // 尝试使用缓存数据
        const cachedData = localStorage.getItem("groupList_cache");
        if (cachedData) {
          try {
            const { data } = JSON.parse(cachedData);
            commit('SET_LIST', data);
            console.warn("groupList 使用缓存数据作为备用");
          } catch (parseError) {
            console.error("groupList 缓存数据解析失败:", parseError);
            commit('SET_LIST', []);
          }
        } else {
          commit('SET_LIST', []);
          console.warn("groupList 使用默认空数据");
        }
      } finally {
        commit("SET_LOADING", false);
      }
    },

    // 加载群组列表（保持向后兼容）
    async loadList({ dispatch }) {
      return dispatch("initialize");
    },
    
    async createGroup({ commit }, groupData) {
      try {
        // 这里需要您提供对应的API
        // const newGroup = await api.createGroup(groupData)
        // commit('ADD_GROUP', newGroup)
        // return newGroup
        
        // 临时实现
        const newGroup = { 
          id: Date.now(), 
          ...groupData,
          createdAt: new Date().toISOString(),
          memberCount: 1,
          isOwner: true,
          lastActiveTime: new Date().toISOString()
        };
        
        commit('ADD_GROUP', newGroup);

        return newGroup;
      } catch (error) {
        console.error('创建群组失败:', error);
        throw error;
      }
    },
    
    async joinGroup({ commit }, id) {
      try {
        // 这里需要您提供对应的API
        // const group = await api.joinGroup(id)
        // commit('ADD_GROUP', group)
        
        // 临时实现
        const group = { id, name: '新群组' }
        commit('ADD_GROUP', group)
      } catch (error) {
        console.error('加入群组失败:', error)
      }
    },
    
    async leaveGroup({ commit }, id) {
      try {
        // 这里需要您提供对应的API
        // await api.leaveGroup(id)
        commit('REMOVE_GROUP', id)
      } catch (error) {
        console.error('退出群组失败:', error)
      }
    },
    
    async disbandGroup({ commit }, id) {
      try {
        // 这里需要您提供对应的API
        // await api.disbandGroup(id)
        commit('REMOVE_GROUP', id)
      } catch (error) {
        console.error('解散群组失败:', error)
      }
    },
    
    // 群组成员
    async loadGroupMembers({ commit }, groupId) {
      try {
        // 这里需要您提供对应的API
        // const members = await api.getGroupMembers(groupId)
        // commit('SET_GROUP_MEMBERS', { groupId, members })
        
        // 临时实现
        const members = []
        commit('SET_GROUP_MEMBERS', { groupId, members })
      } catch (error) {
        console.error('加载群组成员失败:', error)
      }
    },
    
    async addGroupMember({ commit }, { groupId, userId }) {
      try {
        // 这里需要您提供对应的API
        // const member = await api.addGroupMember(groupId, userId)
        // commit('ADD_GROUP_MEMBER', { groupId, member })
        
        // 临时实现
        const member = { id: userId, name: '新成员' }
        commit('ADD_GROUP_MEMBER', { groupId, member })
      } catch (error) {
        console.error('添加群组成员失败:', error)
      }
    },
    
    async removeGroupMember({ commit }, { groupId, userId }) {
      try {
        // 这里需要您提供对应的API
        // await api.removeGroupMember(groupId, userId)
        commit('REMOVE_GROUP_MEMBER', { groupId, userId })
      } catch (error) {
        console.error('移除群组成员失败:', error)
      }
    },
    
    // 群组设置
    async updateGroupSettings({ commit }, { groupId, settings }) {
      try {
        // 这里需要您提供对应的API
        // await api.updateGroupSettings(groupId, settings)
        commit('UPDATE_GROUP_SETTINGS', { groupId, settings })
      } catch (error) {
        console.error('更新群组设置失败:', error)
      }
    },
    
    // 群组邀请
    async sendGroupInvitation({ commit }, { groupId, userIds }) {
      try {
        // 这里需要您提供对应的API
        // const invitation = await api.sendGroupInvitation(groupId, userIds)
        // commit('ADD_GROUP_INVITATION', { type: 'sent', invitation })
        
        // 临时实现
        const invitation = { id: Date.now(), groupId, userIds }
        commit('ADD_GROUP_INVITATION', { type: 'sent', invitation })
      } catch (error) {
        console.error('发送群组邀请失败:', error)
      }
    },
    
    async acceptGroupInvitation({ commit }, invitationId) {
      try {
        // 这里需要您提供对应的API
        // const group = await api.acceptGroupInvitation(invitationId)
        // commit('ADD_GROUP', group)
        // commit('REMOVE_GROUP_INVITATION', { type: 'received', id: invitationId })
        
        // 临时实现
        const group = { id: Date.now(), name: '新群组' }
        commit('ADD_GROUP', group)
        commit('REMOVE_GROUP_INVITATION', { type: 'received', id: invitationId })
      } catch (error) {
        console.error('接受群组邀请失败:', error)
      }
    },
    
    async rejectGroupInvitation({ commit }, invitationId) {
      try {
        // 这里需要您提供对应的API
        // await api.rejectGroupInvitation(invitationId)
        commit('REMOVE_GROUP_INVITATION', { type: 'received', id: invitationId })
      } catch (error) {
        console.error('拒绝群组邀请失败:', error)
      }
    },
    
    // 置顶操作
    async pinGroup({ commit }, id) {
      try {
        // 这里需要您提供对应的API
        // await api.pinGroup(id)
        commit('PIN_GROUP', id)
      } catch (error) {
        console.error('置顶群组失败:', error)
      }
    },
    
    async unpinGroup({ commit }, id) {
      try {
        // 这里需要您提供对应的API
        // await api.unpinGroup(id)
        commit('UNPIN_GROUP', id)
      } catch (error) {
        console.error('取消置顶失败:', error)
      }
    },
    
    // 免打扰操作
    async muteGroup({ commit }, { id, muteUntil }) {
      try {
        // 这里需要您提供对应的API
        // await api.muteGroup(id, muteUntil)
        commit('MUTE_GROUP', { id, muteUntil })
      } catch (error) {
        console.error('设置免打扰失败:', error)
      }
    },
    
    async unmuteGroup({ commit }, id) {
      try {
        // 这里需要您提供对应的API
        // await api.unmuteGroup(id)
        commit('UNMUTE_GROUP', id)
      } catch (error) {
        console.error('取消免打扰失败:', error)
      }
    }
  }
  
  const getters = {
    // 当前群组
    currentGroup: state => {
      return state.list.find(group => group.id === state.currentId)
    },
    
    // 我创建的群组
    createdGroups: state => {
      return state.list.filter(group => group.role === 'owner')
    },
    
    // 我加入的群组
    joinedGroups: state => {
      return state.list.filter(group => group.role && group.role !== 'none')
    },
    
    // 公开群组
    publicGroups: state => {
      return state.list.filter(group => group.type === 'public')
    },
    
    // 私有群组
    privateGroups: state => {
      return state.list.filter(group => group.type === 'private')
    },
    
    // 置顶群组
    pinnedGroups: state => {
      return state.list.filter(group => state.pinnedGroups.includes(group.id))
    },
    
    // 免打扰群组
    mutedGroups: state => {
      return state.list.filter(group => state.muteSettings[group.id]?.isMuted)
    },
    
    // 过滤后的群组列表
    filteredList: state => {
      let list = state.list
      
      // 按类型过滤
      switch (state.filterType) {
        case 'joined':
          list = list.filter(group => group.role && group.role !== 'none')
          break
        case 'created':
          list = list.filter(group => group.role === 'owner')
          break
        case 'public':
          list = list.filter(group => group.type === 'public')
          break
        case 'private':
          list = list.filter(group => group.type === 'private')
          break
        case 'muted':
          list = list.filter(group => state.muteSettings[group.id]?.isMuted)
          break
      }
      
      // 按搜索关键词过滤
      if (state.searchKeyword) {
        const keyword = state.searchKeyword.toLowerCase()
        list = list.filter(group => 
          group.name.toLowerCase().includes(keyword) ||
          group.description?.toLowerCase().includes(keyword)
        )
      }
      
      // 排序
      list.sort((a, b) => {
        let aValue, bValue
        
        switch (state.sortBy) {
          case 'name':
            aValue = a.name
            bValue = b.name
            break
          case 'memberCount':
            aValue = a.memberCount || 0
            bValue = b.memberCount || 0
            break
          case 'lastActivity':
            aValue = a.lastActivity || 0
            bValue = b.lastActivity || 0
            break
          case 'createTime':
            aValue = a.createTime || 0
            bValue = b.createTime || 0
            break
        }
        
        if (state.sortOrder === 'asc') {
          return aValue > bValue ? 1 : -1
        } else {
          return aValue < bValue ? 1 : -1
        }
      })
      
      // 置顶群组放在最前面
      const pinned = list.filter(group => state.pinnedGroups.includes(group.id))
      const unpinned = list.filter(group => !state.pinnedGroups.includes(group.id))
      
      return [...pinned, ...unpinned]
    },
    
    // 待处理的群组邀请
    pendingInvitations: state => {
      return state.groupInvitations.received
    },
    
    // 免打扰状态
    isMuted: state => id => {
      const setting = state.muteSettings[id]
      if (!setting) return false
      
      if (setting.muteUntil && Date.now() > setting.muteUntil) {
        return false
      }
      
      return setting.isMuted
    },
    
    // 置顶状态
    isPinned: state => id => {
      return state.pinnedGroups.includes(id)
    }
  }
  
  export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
  }